package com.sardine.base.hbase.session;

import com.sardine.base.hbase.HBaseConfiguration;
import com.sardine.base.hbase.HDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/11/20
 * Time:15:07
 * hbase的连接工厂
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class HBaseSessionFactoryBean implements FactoryBean<HBaseSessionFactory>, InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(HBaseSessionFactoryBean.class);
    /**
     * 数据源
     */
    private HDataSource dataSource;
    /**
     * 具体实现
     */
    private HBaseSessionFactory sessionFactory;


    /**
     * HBaseSessionFactory builder
     */
    private HBaseSessionFactoryBuilder sessionFactoryBuilder = new HBaseSessionFactoryBuilder();

    public void setDataSource(HDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void setSessionFactory(HBaseSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void setSessionFactoryBuilder(HBaseSessionFactoryBuilder sessionFactoryBuilder) {
        this.sessionFactoryBuilder = sessionFactoryBuilder;
    }

    @Override
    public HBaseSessionFactory getObject() throws Exception {
        if (this.sessionFactory == null) {
            afterPropertiesSet();
        }
        return this.sessionFactory;
    }

    @Override
    public Class<?> getObjectType() {
        return this.sessionFactory == null ? HBaseSessionFactory.class : this.sessionFactory.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (dataSource == null) {
            throw  new RuntimeException("请配置HBaseConfiguration...");
        }
       this.sessionFactory = buildHBaseConnectionFactory();
    }
    /**
     * 创建 HBaseConnectionFactory 对象
     * @return
     * @throws IOException
     */
    protected HBaseSessionFactory buildHBaseConnectionFactory() throws IOException {
        HBaseConfiguration config = new HBaseConfiguration();
        config.setDataSource(dataSource);
        //构建 sessionFactory
        return sessionFactoryBuilder.build(config);
    }
}
